<?php
set_time_limit(0);

include_once (dirname(__FILE__).'/config/database.php');
include_once (dirname(__FILE__).'/class/Log.inc');
include_once (dirname(__FILE__).'/class/Mysql/Exception.inc');
include_once (dirname(__FILE__).'/class/Mysql.inc');

define('LOCK_FILE', dirname(__FILE__).'/lock/bannedUser.lock');
define('LOG_LEVEL', 'DEBUG');

$LogFile = dirname(__FILE__).'/log/bannedUser'.date('Y.m.d').'.log';

$Log = new Zw_Log();
$Log->setCurrLogLevel(LOG_LEVEL);
$Log->setLogFile($LogFile);

$handle = fopen(LOCK_FILE, 'w+');
if(!flock($handle, LOCK_EX|LOCK_NB)){
	$Log->write('进程已经启动，请不要重复启动');
	exit();
}

$GmDb = new Zw_Mysql();
$GmDb->setLog($Log);
$GmDb->connect($gmDatabaseHost, $gmDatabaseUsername, $gmDatabasePassword, $gmDatabaseName);

$GameDb = new Zw_Mysql();
$GameDb->setLog($Log);
$count = 0;
$a=array();
try {
	$fileData = trim(file_get_contents('bannedUser.txt'));
	$dataLine = explode("\n",$fileData);
	foreach($dataLine as $v){
		$ex = explode("\t",$v);
		$operatorFlag = $ex[0];
		$username = $ex[1];
		$roleEx = explode('.',$ex[2]);
		$sid = str_replace('S','',$roleEx[0]);
		$sql = "
			select
				e.`ipAddress`,
				c.`databaseName`,
				c.`gameAreaId`,
				c.`portGroup`
			from
				`t_data_game_area` c
			left join
				`t_data_server_ip` d
			on
				c.`serverId` = d.`serverId`
			left join
				`t_data_ip` e
			on
				d.`ipId` = e.`ipId`
			left join
				`t_cfg_ip_type` f
			on
				e.`ipTypeId` = f.`ipTypeId`
			LEFT JOIN
				`t_data_operator` g
			ON
				c.operatorId = g.operatorId
			where
				g.`operatorFlag` = '{$operatorFlag}'
			AND
				c.`areaNum` = {$sid}
			and
				f.`isDefault` = 1

		";
		$ip = $GmDb->getRow($sql);
		$GameDb->connect($ip['ipAddress'], $gameDatabaseUsername, $gameDatabasePassword, $ip['databaseName']);


		$sql = "
			select
				`usertoken`,
				`userId`
			from
				`t_user`
			where
				`username` = '{$username}'
		";

		if( !(($row = $GameDb->getRow($sql)) === false) ) {
			$userToken = $row['usertoken'];
			$userId = $row['userId'];
			$protocolCode = 61001;
			$host = $ip['ipAddress'];
			$port = ($ip['portGroup']-1)*100+60005;
			$Log->write("token:{$userToken}","DEBUG");
			$Log->write("token:{$host}","DEBUG");
			$Log->write("token:{$port}","DEBUG");

			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if( socket_connect($socket, $host, $port) ) {
				$Log->write("开始发送61001协议","DEBUG");
				$message = '';

				$in = decbin($userId);
				$in = str_pad($in, 64, '0', STR_PAD_LEFT);
				$out = '';

				for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
					$out .= chr(bindec(substr($in,$i,8)));
				}
				$out = strrev($out);

				$message .= $out;
				$message .= pack('s', strlen($userToken));
				$message .= pack('a*', $userToken);
				$encodeMessage = '';
				$parityByte = 0;

				for( $i=0 ; $i < strlen($message) ; $i++ ) {
					$tmpByte = ord(substr($message, $i, 1));
					$parityByte += $tmpByte;
					$tmpByte ^= 0x58;
					$tmpByte = substr(pack('n', $tmpByte), 1, 1);
					$encodeMessage .= $tmpByte;
				}

				$parityByte %= 99;
				$encodeMessage .= substr(pack('n', $parityByte), 1, 1);
				$head = substr(pack('n', 4), 1, 1);
				$head .= pack('S', $protocolCode);
				$head .= pack('l', strlen($encodeMessage)+7);
				$packageBin = $head.$encodeMessage;

				if(!socket_write($socket, $packageBin, strlen($packageBin))) {
					$Log->write("发送数据失败","ERROR");
					return false;
				}

				if( ($output = socket_read($socket, 1024)) !== false ) {
					$resultUnpack = unpack('S', substr($output, 1, 2));
					$Log->write("返回协议号：{$resultUnpack[1]}","DEBUG");

					//禁言成功，封号处理
					$sql = "
						update
							`t_user` a
						left join
							`t_char` b
						on
							a.`userid` = b.`uid`
						set
							b.`enable` = '1'
						where
							a.`userid` = '{$userId}'
					";
					$GameDb->query($sql);

					/*解封
					$sql = "

					insert into
						`t_log_banned_role`
					(
						`type`,
						`gameAreaId`,
						`userId`,
						`operatorUserId`,
						`operatorDateTime`,
						`reason`
					)
					value
					(
						'2',
						'{$ip['gameAreaId']}',
						'{$userId}',
						'1',
						now(),
						'刷元宝'
					)";*/
					$second = 7*24*60*60;
					$sql = "
						insert into
							`t_log_banned_role`
						(
							`type`,
							`gameAreaId`,
							`userId`,
							`unbannedDateTime`,
							`status`,
							`operatorUserId`,
							`operatorDateTime`,
							`reason`
						)
						value
						(
							'1',
							'{$ip['gameAreaId']}',
							'{$userId}',
							from_unixtime(unix_timestamp(now()) + {$second}),
							'1',
							'1',
							now(),
							'刷元宝'
						)
					";
					$GmDb->query($sql);
					//清除元宝

					$sql = "
						update
							`t_user` a
						left join
							`t_char` b
						on
							a.`userid` = b.`uid`
						set
							b.`gold` = '0'
						where
							a.`userid` = '{$userId}'
					";
					$GameDb->query($sql);



					if($resultUnpack[1] != '61002') {
						$Log->write("返回协议号错误","ERROR");
						return false;
					}
				}
				else {
					$Log->write("读取数据失败","ERROR");
					return false;
				}
			}
			else {
				$Log->write("连接端口失败","ERROR");
				return false;
			}
		}
		else {
			$Log->write("获取用户token失败","ERROR");
			return false;
		}



	}
}


catch(Zw_Mysql_Exception $e) {
		$Log->write('数据库错误', 'ERROR');
	}
	catch(Exception $e) {
		$Log->write('系统错误', 'ERROR');
	}
